//common
import http from './index.js'
import db from './db.js'
export default {

	//获取当前时间
	timeToDate(date, flag, value) {
		var date = new Date() //如果date为13位不需要乘1000
		var Y = date.getFullYear() + '-'
		var M =
			(date.getMonth() + 1 < 10 ?
				'0' + (date.getMonth() + 1) :
				date.getMonth() + 1) + '-'
		var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
		var m =
			(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
		var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
		return Y + M + D
	},
	
	payment(amt,goodsId,val,subsId,url,isStatus) {
		let _this = this
		let resData = {
			amt:amt,
			goodsId:Number(goodsId),//套餐id
			orderType:1,
			payChannel:val,
			source:1,
			subsId:subsId,
		}
		http.post('api/pay/sendPay',resData).then(res => {
			if(res.code == 200) {
				let value = res.data
				if(val == "ALIPAY") {
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: res.data.orderInfo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
						success: function(res) {
							uni.showToast({
								title: '支付成功', // 标题
								duration: 1500 // 提示窗停留时间，默认1500ms
							})
							if(isStatus) {
								setTimeout(() => {
									_this.navigateBack()
								},1000)
							}else {
								setTimeout(() => {
									_this.url(url)
								},1000)
							}
						},
						fail: function(err) {
							uni.showToast({
								title: '支付失败', // 标题
								icon: 'none', // 图标类型，默认success
								duration: 1500 // 提示窗停留时间，默认1500ms
							})
						}
					});
				}else {
					uni.requestPayment({
						provider: 'wxpay',
						orderInfo: {
							appid: value.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
							noncestr: value.noncestr, // 随机字符串
							package: value.package, // 固定值
							partnerid: value.partnerid, // 微信支付商户号
							prepayid: value.prepayid, // 统一下单订单号 
							timestamp: value.timestamp, // 时间戳（单位：秒）
							sign: value.sign // 签名，这里用的 MD5/RSA 签名
						},
						success: function(res) {
							uni.showToast({
								title: '支付成功', // 标题
								duration: 1500 // 提示窗停留时间，默认1500ms
							})
							if(isStatus) {
								setTimeout(() => {
									_this.navigateBack()
								},1000)
							}else {
								setTimeout(() => {
									_this.url(url)
								},1000)
							}
						},
						fail: function(err) {
							uni.showToast({
								title: '支付失败', // 标题
								icon: 'none', // 图标类型，默认success
								duration: 3000 // 提示窗停留时间，默认1500ms
							})
						}
					});
				}
			}
		})
	},
	
	/**
	 * 匹配phone
	 */
	isMobile(str) {
		const reg = /^(1[3456789]\d{9})$/
		return reg.test(str)
	},
	// 消息弹出
	show(url,status) {
		if(!status) {
			uni.showToast({
				title: url,
				duration: 2000
			});
		}else {
			uni.showToast({
				title: url,
				icon: "none",
				duration: 2000
			});
		}
	},
	headHeight() {
		//#ifndef MP-ALIPAY
		return uni.getSystemInfoSync()['statusBarHeight']
		//#endif
	},
	// 打电话
	phone(val) {
		uni.makePhoneCall({
			phoneNumber: val //仅为示例
		});
	},
	// 图片预览
	previewImg(img, e) {
		let i = 0
		if (e) {
			i = e
		}
		uni.previewImage({
			current: i,
			urls: img,
			longPressActions: {
				success: function(data) {}
			}
		});
	},

	// 链接
	url(e,status) {
		if (db.get('token') || !status) {
			return uni.navigateTo({
				url: e
			})
		} else {
			this.judgeLogin()
		}
	},

	// 先登录在做操作
	enterOperate(val) {
		if (db.get('token')) {
			return val
		} else {
			this.judgeLogin()
		}
	},

	navigateBack() {
		uni.navigateBack()
	},

	// 链接Tab
	unwatch(e) {
		uni.switchTab({
			url: e
		})
	},
	redirectTo(e,status) {
		if (db.get('token') || status) {
			return uni.redirectTo({
				url: e,
			})
		} else {
			this.judgeLogin()
		}
	},
	reLaunch(e) {
		if (db.get('token') || status) {
			return uni.reLaunch({
				url: e,
			})
		} else {
			this.judgeLogin()
		}
	},
	// 没有登录
	judgeLogin() {
		this.show('请先登录',true)
		// #ifdef MP-WEIXIN
		setTimeout(()=>{
			this.url('/pages/login/miniProgram',true)
		},1000)
		// #endif
		// #ifdef APP-PLUS || H5
		setTimeout(()=>{
			this.url('/pages/login/login')
		},1000)
		// #endif
	},

	// 是否为空
	isEmpty(str) {
		return str.trim() == ''
	},
	// 去重
	unique(arr) {
		var res = [];
		var obj = {};
		for (var i = 0; i < arr.length; i++) {
			if (!obj[arr[i]]) {
				obj[arr[i]] = 1;
				res.push(arr[i]);
			} else {
				this.show('请不要重复添加')
			}
		}
		return res;
	},
	bgColor_000() {
		wx.setNavigationBarColor({
			frontColor: '#000000',
			backgroundColor: '#000000',
			animation: {
				duration: 400,
				timingFunc: 'easeIn'
			}
		})
	},
	// 链接
	guanbi(e) {
		uni.redirectTo({
			url: e
		})
	},
	bgColor_fff() {
		wx.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#ffffff',
			animation: {
				duration: 400,
				timingFunc: 'easeIn'
			}
		})
	},
	// 用户行为上报
	getUser(id) {
		let resData = {
			dict: id
		}
		http.post('userAction/report', resData, true).then(res => {
			if (res.msg == "success") {}
		})
	},
	urlTier(value) {
		let pages = getCurrentPages(); //获取所有页面栈实例列表
		console.log(pages.length)
		if (pages.length > 3) {
			uni.redirectTo({
				url: value
			})
		} else {
			uni.navigateTo({
				url: value
			})
		}
	},
	// app保存图片
	savePhoto(url,isStatus) {
		let _this = this
		// 先下载图片
		uni.downloadFile({
			url,
			success: (resFile) => {
				// #ifdef APP-PLUS
				// 获取到图片本地地址后再保存图片到相册（因为此方法不支持远程地址）
				uni.saveImageToPhotosAlbum({
					filePath: resFile.tempFilePath,
					success: () => {
						if(!isStatus) {
							uni.showToast({
								title: "保存成功！",
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: "保存失败",
						});
					},
				});
				// #endif
				// #ifdef MP-WEIXIN
				if (resFile.statusCode === 200) {
					uni.getSetting({
						success: (res) => {
							if (!res.authSetting["scope.writePhotosAlbum"]) {
								uni.authorize({
									scope: "scope.writePhotosAlbum",
									success: () => {
										uni.saveImageToPhotosAlbum({
											filePath: resFile
												.tempFilePath,
											success: (res) => {
												if(!isStatus) {
													uni.showToast({
														title: "保存成功！",
													});
												}
											},
											fail: (res) => {
												return uni
													.showToast({
														title: res
															.errMsg,
														icon: "none"
													});
											},
											complete: (res) => {},
										});
									},
									fail: () => {
										uni.showModal({
											title: "您已拒绝获取相册权限",
											content: "是否进入权限管理，调整授权？",
											success: (res) => {
												if (res.confirm) {
													uni.openSetting({
														success: (
															res
														) => {
															console
																.log(
																	res
																	.authSetting
																);
														},
													});
												} else if (res
													.cancel) {
													return uni
														.showToast({
															title: "已取消！",
														});
												}
											},
										});
									},
								});
							} else {
								uni.saveImageToPhotosAlbum({
									filePath: resFile.tempFilePath,
									success: (res) => {
										if(!isStatus) {
											uni.showToast({
												title: "保存成功！",
											});
										}
									},
									fail: (res) => {
										return uni.showToast({
											title: res.errMsg,
										});
									},
									complete: (res) => {},
								});
							}
						},
						fail: (res) => {},
					});
				} else {
					return uni.showToast({
						title: resFile.errMsg,
					});
				}
				// #endif
			},
		});
	},
	wxPayment() {
		console.log(111)
		return 222
		uni.requestPayment({
		    provider: 'wxpay',
			timeStamp: String(Date.now()),
			nonceStr: 'A1B2C3D4E5',
			package: 'prepay_id=wx20180101abcdefg',
			signType: 'MD5',
			paySign: '',
			success: function (res) {
				
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			}
		});
	},
	bgColor_000() {
		wx.setNavigationBarColor({
		  frontColor: '#000000',
		  backgroundColor: '#000000',
		  animation: {
			duration: 400,
			timingFunc: 'easeIn'
		  }
		})
	},
	bgColor_fff() {
		wx.setNavigationBarColor({
		  frontColor: '#ffffff',
		  backgroundColor: '#ffffff',
		  animation: {
			duration: 400,
			timingFunc: 'easeIn'
		  }
		})
	},
	// 点击联系客服
	customerService() {
		plus.share.getServices(function(res) {
			var sweixin = null;
			for (var i = 0; i < res.length; i++) {
			  var t = res[i];
			  if (t.id == 'weixin') {
				sweixin = t;
			  }
			}
			if (sweixin) {
			  sweixin.launchMiniProgram({
				id: 'gh_1d737acfd4db',  // 小程序原始id
				type: 0,  // 0-正式版； 1-测试版； 2-体验版。 默认值为0
			  });
			} else {
			  plus.nativeUI.alert('当前环境不支持微信操作!');
			}
		}, function(res) {
			console.log(JSON.stringify(res));
		});
	},
	// 跳转到微信
	weixinClick(value,title) {
		if(!title) {
			title = ''
		}
		let _this = this
		uni.setClipboardData({
			data: value,
			success: function () {
				_this.show(title + '复制成功',true)
			}
		});
		setTimeout(() => {
			var UIApplication = plus.ios.import('UIApplication');
			var NSURL = plus.ios.import('NSURL');
			var setting = NSURL.URLWithString(`weixin://`);
			var application = UIApplication.sharedApplication();
			application.openURL(setting);
			plus.ios.deleteObject(setting);
			plus.ios.deleteObject(application);
		},1000)
	},
	// 复制文字
	copyClick(value,title) {
		if(!title) {
			title = ''
		}
		let _this = this
		uni.setClipboardData({
			data: value,
			success: function () {
				_this.show(title + '复制成功',true)
			}
		});
	},
	// 微信小程序支付
	wxPayment(orderId,status) {
		let _this = this
		let resData = {
			orderId,
			payChannel:'JSAPI'
		}
		http.post('pay/sendBuy',resData).then(res => {
			if(res.code == 200) {
				let value = res.data
				uni.requestPayment({
				    provider: 'wxpay',
					timeStamp: value.timeStamp,
					nonceStr: value.nonceStr,
					package: value.package,
					signType: 'MD5',
					paySign: value.paySign,
					success: function (res) {
						uni.showToast({
							title: '支付成功', // 标题
							duration: 1500 // 提示窗停留时间，默认1500ms
						}) 
						setTimeout(() => {
							_this.wSucceedClick(orderId,status)
						},1000)
					},
					fail: function (err) {
						uni.showToast({
							title: '支付失败', // 标题
							icon:"none",
							duration: 1500 // 提示窗停留时间，默认1500ms
						})
						setTimeout(() => {
							_this.wSucceedClick(orderId,status)
						},1000)
						console.log('fail:' + JSON.stringify(err));
					}
				})
			}
		})
	},
	// 微信小程序支付完成的回调
	wSucceedClick(orderId,status) {
		if(status) {
			this.redirectTo(`/pages/my/orderDetails?orderId=${orderId}&status=true`)
		}else {
			this.url(`/pages/my/orderDetails?orderId=${orderId}&status=true`)
		}
		// http.post('user/orderInfoV2',{orderId}).then(res => {
		// 	if(res.code == 200) {
		// 		for(var i = 0; i < res.data.length; i++) {
		// 			this.savePhoto(res.data[i],true)
		// 			if(i == res.data.length -1) {
		// 				uni.showToast({
		// 					title: "保存成功！",
		// 				});
		// 			}
		// 		}
		// 	} 
		// })
	},
	// 生成随机数
	randomNumber(len) {
		let chars = '0123456789';
		let maxPos = chars.length;
		let str = '';
		for (let i = 0; i < len; i++) {
			str += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return str;
	}
	// getHeight() {
	// 	uni.getSystemInfo({
	// 		success(res) {
	// 			return res.screenHeight
	// 			console.log(res.screenHeight); //屏幕高度  注意这里获得的高度宽度都是px 需要转换rpx
	// 		}
	// 	})
	// }
}
